<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Db\Column;
use Phalcon\Di;
use StarCloud\Api\Library\Exception;
use StarCloud\Library\ArraySort;
use StarCloud\Library\HttpCurl;
use StarCloud\Models\Doumvip\FanqieBook;
use StarCloud\Models\Doumvip\FanqieBookDetail;
use StarCloud\Models\Doumvip\TiktokNew;

class XunleiBot
{
    use HttpCurl;

    /* @var $httpClient HttpClient */
    private $httpClient = null;

    public function __construct()
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getHeader()
    {
        return [
            'Authorization' => $this->getAccessToken(),
        ];
    }

    public function getAccessToken()
    {
        $key = "xl_access_token_20250101";
        $tokenData = $this->getCache($key);
        $tokenData = json_decode($tokenData, true);
        return $tokenData['token_type'] . ' ' . $tokenData['access_token'];
    }

    public function refreshToken()
    {
        $key = "xl_access_token_20250101";
        $tokenData = $this->getCache($key);

        if (empty($tokenData)) {
            $tokenData = [
                "token_type" => "Bearer",
                "access_token" => "eyJhbGciOiJSUzI1NiIsImtpZCI6ImZjNDE2MTBkLTY4YzAtNGFkMy04YTQ4LTA3MzdkMjE1YTBkMyJ9.eyJpc3MiOiJodHRwczovL3hsdXNlci1zc2wueHVubGVpLmNvbSIsInN1YiI6IjkyODEwODEwMyIsImF1ZCI6IlhXNVNrT2hMRGpuT1pQN0oiLCJleHAiOjE3MzU4NzY4NjMsImlhdCI6MTczNTg2OTY2MywiYXRfaGFzaCI6InIubG5sTlk4bDJFZS1QVkZMOUVzeXBadyIsInNjb3BlIjoidXNlciBwYW4gcHJvZmlsZSBvZmZsaW5lIiwicHJvamVjdF9pZCI6IjJydms0ZTNna2RubDd1MWtsMGsiLCJtZXRhIjp7ImEiOiJZUGxFT1B1eEloTEVCdG52cEZYSm5RKzN4UVgrR29vZzhPdGhxbXN3ZGgwPSJ9fQ.fpR4G02JyD0VY2vZk7DuxKo2knmFnzhNpAz4oPWK2OFxGGIx2XV9H225uBFLq1L-ePwKNo6ASJfjIlIA9NDasNgczBhoRxBl-Zw4qOLvbcjrBnypPOy7MXTHAcOTyP7sHg-MasG-768zU5NT8NyBZU8vJ-gjXHAVQxzQairWbxGTWDv2-2Qgof5Z2vxe_EYjHyk9f8RwdxbGpqwxD9Y2Jl5FOHs-u42L-eqcgX0pUx1QZ5iXIFbrQlFhh1ao4PS9P0rVt6WDvX5e6t5Js-Rrs5qWq-R6dNv2VmwT59EXjw4n-tMs_23arrqskIF801nfCDpcJfbYKnqpv7BEmrQoZQ",
	            "refresh_token" => "a1.qaiN3Ghv4Gd3RN8IQaYJDn4_H9zHoAzJ4190y97tp-Fo9xjlKwjZ",
                "expires_in" =>  7200,
                'id_token' => '',
                "sub" => "928108103",
                "user_id" => "928108103",
                "user_group" => [
                    "vip_1_3_5"
                ],
                "client_id" => "XW5SkOhLDjnOZP7J"
            ];
        } else {
            $tokenData = json_decode($tokenData, true);
        }

        $url = "https://xluser-ssl.xunlei.com/v1/auth/token";
        $body = [
            "refresh_token" => $tokenData['refresh_token'],
            "grant_type" => "refresh_token",
            "client_id" => $tokenData['client_id'],
        ];
        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        var_dump($json);

        if (isset($json['access_token']) && isset($json['refresh_token'])) {
            $tokenData['access_token'] = $json['access_token'];
            $tokenData['refresh_token'] = $json['refresh_token'];
            $tokenData['id_token'] = $json['id_token'] ?? '';
            $this->setCache($key, json_encode($tokenData), $json['expires_in'] - 100);
            return $tokenData;
        }

        return false;
    }
    public function getShuliangOrder($startDate, $endDate)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/password/new/share_data?begin={$startDate}&end={$endDate}&quality_score=invalid_income&activity_type=0&type=1";

        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data'])) {
            return $json['data'];
        }

        return null;
    }

    public function createGmCode($code)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/xlacc/redeemcode";
        $body = [
                "code" => "$code",
                "status" => "0",
                "ownerName" => "丰霜",
                "ownerUid" => "1916845200",
                "operator" => "Union_202311297"
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 200) {
            return true;
        }

        throw new \StarCloud\Library\Exception(9999, $json['msg']);
    }

    public function unbind($uid)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/unbind?uid={$uid}";
        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return true;
        }

        return false;
    }

    public function getQueryOrder($startDate, $endDate)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/data?begin={$startDate}&end={$endDate}";

        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['income']) && $json['income'] > 0) {
            return $json['data'];
        }

        return null;
    }

    public function getQueryShareOrderType1($startDate, $endDate)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/password/new/share_data?begin={$startDate}&end={$endDate}&type=1";
        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data']) && count($json['data']) > 0) {
            return $json['data'];
        }

        return null;
    }

    public function getQueryShareOrder($startDate, $endDate)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/password/new/share_data?begin={$startDate}&end={$endDate}";


        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data']) && count($json['data']) > 0) {
            return $json['data'];
        }

        return null;
    }

    public function kuorong($record, $amount)
    {
        $url = 'https://drive-union.xunlei.com/drive/v1/union/bitchAddQuantityOrder';

        $body = [
            'usernewnos' => [$record['uid']],
            'remark' => "",
            'origin_qty' => $amount,
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return true;
        }

        if (strpos($json['message'], "只允许绑定下级链接") !== false) {
            throw new \StarCloud\Library\Exception(9999, "链接不归属于抖啦咪迅雷联盟, 请确定您是否已成功报备");
        }

        throw new \StarCloud\Library\Exception(9999, $json['message']);
    }

    public function openVip($record, $vip_type = 1)
    {
        $url = 'https://drive-union.xunlei.com/drive/v1/union/bitchAddVipQuantityOrder';

        $body = [
            'origin_qty' => 1,
            'usernewnos' => [$record['uid']],
            'remark' => "",
            'vip_type' => $vip_type,
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return true;
        }

        if (strpos($json['message'], "只允许绑定下级链接") !== false) {
            throw new \StarCloud\Library\Exception(9999, "链接不归属于抖啦咪迅雷联盟, 请确定您是否已成功报备");
        }

        throw new \StarCloud\Library\Exception(9999, $json['message']);
    }

    public function getUserByPhone($phone)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/bind/data?start_date=&end_date=&phone_no=".$phone;

        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        Di::getDefault()->get("logger")->info(__FUNCTION__ . json_encode($json));
        if (isset($json['code']) && $json['code'] == 200) {
            if (isset($json['data'][0]) && $json['data'][0]['phone_no'] == $phone   ) {
                return $json['data'][0];
            }
            return false;
        }

        return null;
    }

    public function createKeyWord($blogName, $link, $keyword, $category)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/password/add";
        $body = [
            'category' => $category,
            'content' => $keyword,
            'link' => $link,
            'sub_union_name' => $blogName,
        ];
        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return true;
        }

        if (strpos($json['message'], "只允许绑定下级链接") !== false) {
            throw new \StarCloud\Library\Exception(9999, "链接不归属于抖啦咪迅雷联盟, 请确定您是否已成功报备");
        }

        throw new \StarCloud\Library\Exception(9999, $json['message']);

    }

    public function isDeleteKeyword($keyword)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/password/data?start_date=&end_date=&content={$keyword}&name=&status=1&category=";

        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (ENV_CLI) {
            var_dump($json);
        }

        if (isset($json['code']) && $json['code'] == 0 && count($json['data']) > 0) {
            return true;
        }

        return false;
    }

    public function getKeywordItem($keyword)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/password/data?start_date=&end_date=&content={$keyword}&name=&status=0&category=";

        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);


        if (isset($json['code']) && $json['code'] == 0 && count($json['data']) > 0) {
            return $json['data'][0];
        }

        return false;
    }


    public function createGroupKeyWord($link, $keyword, $usernewno)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/password/add";
        $body = [
            'type' => 3,
            'content' => $keyword,
            'link' => $link,
            'usernewno' => $usernewno,
        ];
        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return true;
        }

        if (strpos($json['message'], "只允许绑定下级链接") !== false) {
            throw new \StarCloud\Library\Exception(9999, "链接不归属于抖啦咪迅雷联盟, 请确定您是否已成功报备");
        }

        throw new \StarCloud\Library\Exception(9999, $json['message']);

    }

    public function updateKeyword($item)
    {
        $url = "https://drive-union.xunlei.com/drive/v1/union/password/update";
        $body = $item;
        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return true;
        }

        throw new \StarCloud\Library\Exception(9999, $json['message']);
    }
}
